package com.shizhanzhe.qdd.apprentice;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shizhanzhe.qdd.R;
import com.shizhanzhe.qdd.apprentice.bean.SzBean;
import com.shizhanzhe.qdd.base.UserBean;
import com.shizhanzhe.qdd.home.activity.ApprenticeAwardActivity;
import com.shizhanzhe.qdd.home.activity.ApprenticeDetailsActivity;
import com.shizhanzhe.qdd.home.activity.LoginActivity;
import com.shizhanzhe.qdd.home.dialog.ExitDialog;
import com.shizhanzhe.qdd.url.Path;
import com.shizhanzhe.qdd.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.qdd.utils.Util;
import com.shizhanzhe.qdd.utils.a;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by YJ on 2019/1/3.
 * 收徒赚钱
 */
public class ApprenticeFragment extends Fragment {
    Unbinder unbinder;
    @BindView(R.id.stjl)
    TextView stjl;
    @BindView(R.id.yxtd)
    TextView yxtd;
    @BindView(R.id.stzs)
    TextView stzs;
    //    @BindView(R.id.tszs)
//    TextView tszs;
    @BindView(R.id.dqjb)
    TextView dqjb;
    @BindView(R.id.regular)
    TextView regular;
    @BindView(R.id.jrst)
    TextView jrst;
    @BindView(R.id.wxfx)
    LinearLayout wxfx;
    @BindView(R.id.stm)
    TextView stm;
    @BindView(R.id.copy_1)
    TextView copy1;
    @BindView(R.id.edit_1)
    EditText edit1;
    @BindView(R.id.copy_2)
    TextView copy2;
    @BindView(R.id.edit_2)
    EditText edit2;
    @BindView(R.id.tv)
    TextView tv;
    private ClipboardManager cm;
    private SzBean szBean;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_apprentice, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getYM();
        stm.setText("" + UserBean.uid);
        regular.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        regular.getPaint().setAntiAlias(true);//抗锯齿
        if (UserBean.uid != 0) {
            stzMoney();
        } else {
            stjl.setText("0.0");
            dqjb.setText("当前级别：游客");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    IWXAPI iwxapi;
    String appid = "";
    String appname = "";

    public void send(Context paramContext, int paramInt, String url, String title, String desc) {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        iwxapi = WXAPIFactory.createWXAPI(paramContext, "wx597d8e43a8463f61", true);
        // 将应用的appId注册到微信
        iwxapi.registerApp("wx597d8e43a8463f61");
        WXWebpageObject localWXWebpageObject = new WXWebpageObject();
        localWXWebpageObject.webpageUrl = url;
        WXMediaMessage wxMediaMessage = new WXMediaMessage(localWXWebpageObject);
        wxMediaMessage.title = title;
        wxMediaMessage.description = desc;
        wxMediaMessage.thumbData = Util.bmpToByteArray(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.logo), 150, 150, true), true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = wxMediaMessage;
        req.scene = paramInt;
        iwxapi.sendReq(req);
        Bundle bundle = new Bundle();
        req.toBundle(bundle);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        intent.setClassName("com.tencent.mm", "com.tencent.mm.plugin.base.stub.WXEntryActivity");
        intent.putExtra("_mmessage_sdkVersion", 620824064);
        intent.putExtra("_mmessage_appPackage", appname);
        intent.putExtra("_mmessage_content", appid);
        intent.putExtra("_mmessage_checksum", a.a(appid, 620824064, "com.shizhanzhe.zxb"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        paramContext.startActivity(intent);
    }

    private static String buildTransaction(String paramString) {
        if (paramString == null) {
        }
        for (paramString = String.valueOf(System.currentTimeMillis()); ; paramString = paramString + System.currentTimeMillis()) {
            return paramString;
        }
    }

    @OnClick({R.id.wxfx, R.id.stm, R.id.copy_1, R.id.copy_2, R.id.regular, R.id.ll_yxtd, R.id.ll_stzs})
    public void onViewClicked(View view) {
        if (UserBean.uid != 0) {
            switch (view.getId()) {
                case R.id.wxfx:

                    if (Util.isInstallApp(getContext(), "com.tencent.mobileqq")) {
                        appid = "weixin://sendreq?appid=wxf0a80d0ac2e82aa7";
                        appname = "com.tencent.mobileqq";
                    } else if (Util.isInstallApp(getContext(), "com.tencent.mtt")) {
                        appid = "weixin://sendreq?appid=wx64f9cf5b17af074d";
                        appname = "com.tencent.mtt";
                    } else if (Util.isInstallApp(getContext(), "com.ss.android.article.news")) {
                        appid = "weixin://sendreq?appid=wx50d801314d9eb858";
                        appname = "com.ss.android.article.news";
                    } else {
                        final ExitDialog mdelDialog = new ExitDialog(getContext());
                        mdelDialog.setExitListener(new ExitDialog.ExitListener() {
                            @Override
                            public void chooseTrue() {
                                //确定清除
                                mdelDialog.dismiss();
                                Uri content_url = Uri.parse("http://migmkt.qq.com/qbrowser/newindex_22060.html");
                                startActivity(new Intent(Intent.ACTION_VIEW, content_url));
                            }

                            @Override
                            public void chooseFalse() {
                                //取消
                                mdelDialog.dismiss();
                            }
                        });
                        mdelDialog.show();
                        mdelDialog.downQQ();
                        return;
                    }
                    send(getContext(), 0, ym+"/yum.php?uid=" + UserBean.uid+"&type=1", "快来加入钱多多", "分享资讯就能赚钱！");
                    break;
                case R.id.stm:
                    cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setText(UserBean.uid + "");
                    Toast.makeText(getContext(), "复制成功", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.copy_1:
                    cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setText(edit1.getText().toString());
                    Toast.makeText(getContext(), "复制成功", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.copy_2:
                    cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setText(edit1.getText().toString());
                    Toast.makeText(getContext(), "复制成功", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.regular:
                    startActivity(new Intent(getActivity(), ApprenticeAwardActivity.class).putExtra("yxtd", szBean.getData().getYxtd()).putExtra("levelname", szBean.getData().getStjb()));
                    break;
                case R.id.ll_yxtd:
                    startActivity(new Intent(getActivity(), ApprenticeDetailsActivity.class).putExtra("type", 4).putExtra("tdzs", szBean.getData().getTdzs()).putExtra("yxtd", szBean.getData().getYxtd()));
                    break;
                case R.id.ll_stzs:
                    startActivity(new Intent(getActivity(), ApprenticeDetailsActivity.class).putExtra("type", 5).putExtra("tdzs", szBean.getData().getTdzs()).putExtra("yxtd", szBean.getData().getYxtd()));
                    break;
                default:
            }
        } else {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }

    }

    private void stzMoney() {
        OkHttpDownloadJsonUtil.downloadJson(getContext(), Path.stzMoney(UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onsendJson(String json) {
                try {
                    szBean = new Gson().fromJson(json, SzBean.class);
                    stjl.setText("" + szBean.getData().getStjl());
                    yxtd.setText(szBean.getData().getYxtd() + "");
                    stzs.setText(szBean.getData().getTdzs() + "");
//                    tszs.setText(szBean.getData().getTszs()+"");
                    dqjb.setText("当前级别：" + szBean.getData().getStlevel() + "级  " + szBean.getData().getStjb());
                    jrst.setText(szBean.getData().getJrst() + "");
                    edit1.setText(szBean.getData().getTdst1() + UserBean.inviteurl);
                    edit2.setText(szBean.getData().getTdst2() + UserBean.inviteurl);
                    UserBean.level = szBean.getData().getStlevel();
                } catch (Exception e) {
                    Toast.makeText(getContext(), "数据异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    String ym = "";

    private void getYM() {
        OkHttpDownloadJsonUtil.downloadJson(getContext(), "http://zxbshare.itqzw.com/index.php/index/index/domain", new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    ym = object.optString("domain");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (UserBean.uid != 0) {
            stm.setText("" + UserBean.uid);
            stzMoney();
        } else {
            stjl.setText("0.0");
            dqjb.setText("当前级别：游客");
        }
    }

    public boolean isQQweb() {
        PackageManager manager = getContext().getPackageManager();
        List<PackageInfo> pkgList = manager.getInstalledPackages(0);
        for (int i = 0; i < pkgList.size(); i++) {
            PackageInfo pI = pkgList.get(i);
            if (pI.packageName.equalsIgnoreCase("com.tencent.mtt")) {
                return true;
            }
        }
        return false;
    }
}
